import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())

  // 基础配置
  const baseConfig = {
    plugins: [
      vue()
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    }
  }

  // 开发服务器配置
  const devConfig = {
    server: {
      port: 3005,
      open: true,
      proxy: {
        '/file': {
          target: env.VITE_API_BASE_URL + '/upms',
          changeOrigin: true,
        },
        '/api': {
          target: env.VITE_API_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
  }

  // 库构建配置
  const libBuildConfig = {
    build: {
      lib: {
        entry: path.resolve(__dirname, 'src/index.ts'),
        name: 'WorkfoxFormGenerator',
        fileName: (format) => `workfox-form-generator.${format}.js`,
        formats: ['es', 'umd']
      },
      rollupOptions: {
        external: ['vue', 'element-plus', 'vuedraggable'],
        output: {
          globals: {
            vue: 'Vue',
            'element-plus': 'ElementPlus',
            vuedraggable: 'vuedraggable'
          },
          exports: 'named'
        },
      },
      outDir: 'dist',
      sourcemap: false,
    },
  }

  // 根据模式返回配置
  if (mode === 'lib') {
    return {
      ...baseConfig,
      ...libBuildConfig,
    }
  } else {
    return {
      ...baseConfig,
      ...devConfig
    }
  }
})